//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import { appWindow, WebviewWindow } from "@tauri-apps/api/window";
import { sleep } from "./time";
import { get_assistant_mode, type LocalRepoInfo } from "@/api/local_repo";
import { USER_TYPE } from "@/api/user";

export async function openGitAssistant(repoInfo: LocalRepoInfo, userName: string, userType: USER_TYPE, extraToken: string) {
    const mode = await get_assistant_mode();
    if (mode == "simple") {
        await openGitSimple(repoInfo, userName, userType, extraToken);
    } else {
        await openGitPro(repoInfo, userName, userType, extraToken);
    }
}

async function openGitSimple(repoInfo: LocalRepoInfo, userName: string, userType: USER_TYPE, extraToken: string) {
    let tmpUserName = userName;
    const parts = tmpUserName.split(":",2);
    if(parts.length > 1){
        tmpUserName= parts[1];
    }

    const label = `gitsimple:${repoInfo.id.replaceAll("-", "")}`;
    const view = WebviewWindow.getByLabel(label);
    if (view != null) {
        await view.setAlwaysOnTop(true);
        await sleep(500);
        await view.setAlwaysOnTop(false);
        return;
    }

    const pos = await appWindow.innerPosition();

    new WebviewWindow(label, {
        url: `git_simple.html?id=${encodeURIComponent(repoInfo.id)}&username=${encodeURIComponent(tmpUserName)}&usertype=${userType}&token=${encodeURIComponent(extraToken)}`,
        width: 1300,
        minWidth: 1300,
        height: 800,
        minHeight: 800,
        title: `本地Git仓库(${repoInfo.name})`,
        resizable: true,
        x: pos.x + Math.floor(Math.random() * 200),
        y: pos.y + Math.floor(Math.random() * 200),
    });
}

async function openGitPro(repoInfo: LocalRepoInfo, userName: string, userType: USER_TYPE, extraToken: string) {
    let tmpUserName = userName;
    const parts = tmpUserName.split(":",2);
    if(parts.length > 1){
        tmpUserName= parts[1];
    }

    const label = `gitpro:${repoInfo.id.replaceAll("-", "")}`;
    const view = WebviewWindow.getByLabel(label);
    if (view != null) {
        await view.setAlwaysOnTop(true);
        await sleep(500);
        await view.setAlwaysOnTop(false);
        return;
    }

    const pos = await appWindow.innerPosition();

    new WebviewWindow(label, {
        url: `git_pro.html?id=${encodeURIComponent(repoInfo.id)}&username=${encodeURIComponent(tmpUserName)}&usertype=${userType}&token=${encodeURIComponent(extraToken)}`,
        width: 1300,
        minWidth: 1300,
        height: 800,
        minHeight: 800,
        title: `本地Git仓库(${repoInfo.name})`,
        resizable: true,
        x: pos.x + Math.floor(Math.random() * 200),
        y: pos.y + Math.floor(Math.random() * 200),
    });
}